from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import datetime
from flask import current_app
from flask_login import UserMixin

db = SQLAlchemy()

class User(db.Model,UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    login_attempts = db.Column(db.Integer, default=0)
    locked_until = db.Column(db.DateTime)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(
            password + current_app.config['SECURITY_PASSWORD_SALT'],
            method='pbkdf2:sha256:600000'
        )
    
    def check_password(self, password):
        return check_password_hash(
            self.password_hash, 
            password + current_app.config['SECURITY_PASSWORD_SALT']
        )
    
    def is_locked(self):
        if self.locked_until:
            return self.locked_until > datetime.datetime.utcnow()
        return False
    
    def get_id(self):
        return str(self.id)